<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>图片水印</title>
  <style>
    * {
      margin: 0;
      padding: 0;
    }

    #div1 {
      margin: 100px auto;
      width: 500px;
      height: 900px;
      border: 1px solid black;
    }

    #div1 img {
      width: 100%;
      display:block;
    }

    .button1 {
      position: absolute;
      width: 20px;
      height: 20px;
      background: blue;
      z-index: 10;
      border: 1px solid black;
      border-radius: 10px;
    }

    #img-container {
      position: relative;
      width: 100%;
      background: red;
      border: 1px dashed green;
      box-sizing: border-box;
    }

    .button1>label {
      color: white;
    }
  </style>
</head>

<body>
  <div id="div1" onclick="clickAction()">
    <div id="img-container">
      <img id="car01" src="./img/car01.png">
    </div>
  </div>
  <script>

    function clickAction() {
      let car01 = document.getElementById("car01");
      let objTop = getOffsetTop(car01);// 对象x位置
      let objLeft = getOffsetLeft(car01);// 对象y位置

      // event.clientX 点击时间相对于屏幕 x 坐标
      let mouseX = event.clientX + document.body.scrollLeft; // 鼠标x位置
      let mouseY = event.clientY + document.body.scrollTop; // 鼠标y位置

      // 计算点击的相对位置
      let objX = mouseX - objLeft;
      let objY = mouseY - objTop;
      console.log(objX + "," + objY);
      addButton(objX, objY);
    }

    function addButton(x, y) {
      let inputElement = document.createElement("input");
      inputElement.type = "button";
      inputElement.className = "button1"
      inputElement.style.left = (x - 10) + "px";
      inputElement.style.top = (y - 10) + "px";
      inputElement.onclick = buttonClickAction;
      inputElement.zIndex = 10;
      let imgContainer = document.getElementById("img-container");
      imgContainer.appendChild(inputElement);
    }

    function buttonClickAction() {
      // 阻止点击事件穿透
      event.stopPropagation();
      console.log("buttonClickAction");
    }

    
    function getOffsetTop(obj) {
      let tmp = obj.offsetTop;
      let val = obj.offsetParent;
      while (val != null) {
        tmp += val.offsetTop;
        val = val.offsetParent;
      }
      return tmp;
    }

    function getOffsetLeft(obj) {
      let tmp = obj.offsetLeft;
      let val = obj.offsetParent;
      while (val != null) {
        tmp += val.offsetLeft;
        val = val.offsetParent;
      }
      return tmp;
    }

  </script>
</body>

</html>